﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace ECommerce.Web.Models
{
    public class Basket : Entity
    {
        public virtual Shopper Shopper { get; set; }
        public virtual DateTime DateIssued { get; set; }
        public virtual DateTime LastDateContentsChanged { get; set; }
        
        private IList<BasketItem> items = new List<BasketItem>();

        public virtual IEnumerable<BasketItem> Items
        {
            get { return this.items; }
            protected set { this.items = value.ToList(); }
        }

        public virtual void AddProduct(Product product, int quantity)
        {            
            BasketItem basketItemForProduct = this.items.SingleOrDefault(x => x.Product.Id == product.Id);

            if (basketItemForProduct == null)
            {
                BasketItem item = new BasketItem();

                item.Basket = this;
                item.Product = product;
                item.Quantity = quantity;

                this.items.Add(item);
            }
            else
            {
                basketItemForProduct.Quantity += quantity;
            }

            UpdateLastDateContentsChanged();
        }

        public virtual void RemoveProduct(Product product)
        {
            BasketItem basketItemToRemove = this.items.SingleOrDefault(x => x.Product.Id == product.Id);

            if (basketItemToRemove == null)
            {
                return;
            }

            this.items.Remove(basketItemToRemove);

            UpdateLastDateContentsChanged();
        }

        public virtual void ChangeProductQuantity(Product product, int quantity)
        {
            BasketItem basketItem = this.items.SingleOrDefault(x => x.Product.Id == product.Id);

            if (basketItem == null)
            {
                return;
            }

            basketItem.Quantity = quantity;

            UpdateLastDateContentsChanged();
        }

        public virtual void AddBasketItem(BasketItem item)
        {
            item.Basket = this;
            this.items.Add(item);

            UpdateLastDateContentsChanged();
        }

        public virtual void RemoveBasketItem(BasketItem item)
        {
            this.items.Remove(item);

            UpdateLastDateContentsChanged();
        }


        private void UpdateLastDateContentsChanged()
        {
            LastDateContentsChanged = SystemTime.Now();
        }

        public virtual decimal GetSubTotal()
        {
            return this.items.Sum(x => x.GetTotal());
        }
    }
}
